package jvm_argument;

import java.text.DecimalFormat;

//设置最大堆内存大小
public class Demo1 {

    public static void main(String[] args) throws InterruptedException {
        //分配1M
        byte[] bytes1  = new byte[1 * 1024 * 1024];
        System.out.println("分配1M");
        SystemOutJvmInfo();
        Thread.sleep(3000);
        byte[] bytes2 = new byte[4 * 1024 * 1024];
        System.out.println("分配4m");
        Thread.sleep(3000);
        SystemOutJvmInfo();

    }

    public static  void  SystemOutJvmInfo(){
        //获取最大内存
        Long maxMemory = Runtime.getRuntime().maxMemory();
        System.out.println("MaxMemory：" + maxMemory + "，转换为M:" + toMStr(maxMemory));
        //当前空闲内存
        Long freeMemory = Runtime.getRuntime().freeMemory();
        System.out.println("freeMemory：" + freeMemory + "，转换为M :" + toMStr(freeMemory));
        //已使用内存
        Long useMemory = Runtime.getRuntime().totalMemory();
        System.out.println("useMemory：" + useMemory + "，转换为M" + toMStr(useMemory));
    }

    public static String toMStr(Long kb){
        float num = kb / (1024*1024);
        DecimalFormat dlf = new DecimalFormat("0.00");
        String result = dlf.format(num);
        return result;
    }
}
